let Utils = require("../../framework/js/utils");

if (!window.aui) {
    window.aui = {};
}

window.aui.Utils = Utils;

window.aui.createModal = function (name, instance) {
    return instance;
};

window.aui.createCityLinkComponent = function (type) {
    var ret = {
        defaultprovinceoptions: [{
            label: "请选择省份",
            value: ""
        }],
        defaultcityoptions: [{
            label: "请选择城市",
            value: ""
        }]
    };

    ret.data = function (context) {
        ret.provinceoptions = ret.defaultprovinceoptions;
        ret.cityoptions = ret.defaultcityoptions;
    };

    ret.refreshProvince = function (context) {
        return window.aui.Net.all("areas", {
            token: rootcontroller.tokenManager.getToken()
        }).then(function (response) {
            if (!response.data.data || response.data.data.length < 1) {
                console.error("没有数据返回")
            }
            ret.provinceoptions = ret.defaultprovinceoptions.concat(response.data.data.map(function (v) {
                v.label = v.display_name;
                v.value = v.data;
                return v;
            }));
            if (!ret.init) {
                ret.init = true;
                if (ret.firstLoad) {
                    ret.firstLoad();
                }
            }
        });
    };

    ret.refreshCity = function (context, value, cb) {
        return window.aui.Net.all("areas", {
            data: value
        }).then(function (response) {
            if (!response.data.data || response.data.data.length < 1) {
                console.error("没有数据返回")
            }
            ret.cityoptions = ret.defaultcityoptions.concat(response.data.data.map(function (v) {
                v.label = v.display_name;
                v.value = v.data;
                return v;
            }));

            if (cb) {
                cb();
            }
        });
    };

    ret.mounted = function (context) {
        ret.context = context;
        ret.init = false;
        ret.s = 1;
        ret.refreshProvince(context);
    };


    ret.wanttorefresh = false;

    ret.onMainChange = function (form, value) {    
        ret.mustReset().then(function () {
            if (value === 0 || value) {
                ret.wanttorefresh = true;
                ret.refreshCity(ret.context, value);
            } else {
                ret.wanttorefresh = false;
                setTimeout(function() {
                    ret.cityoptions = ret.defaultcityoptions;      
                }, 0);
            }
        })       
    };

    ret.onSubOpen = function () {
        if (ret.wanttorefresh) {
            if (ret.onSubOpenAndRefresh) {
                ret.onSubOpenAndRefresh();
            }
        }
    };

    return ret;
};

window.aui.gloablDatatableDefine = {
    "remark": {
        key: function (item) {
            return "备注";
        },
        value: function (item) {
            return {
                componentname: "aui-truncate-text",
                value: item.remark,
                len: 30
            };
        }
    },
    "enums": function (key, enums, setvalue, options) {
        var res = {
            key: function (item) {
                return key;
            },
            value: function (item) {
                return {
                    componentname: 'aui-enums-translate',
                    enums: enums,
                    value: setvalue(item)
                }
            }
        };
        return Object.assign(res, options);
    },
};

window.aui._lasttoast = {};
window.aui.toast = function (toast) {
    if (toast.text !== window.aui._lasttoast.text && toast.icon !== window.aui._lasttoast.icon && toast.heading !== window.aui._lasttoast.heading) {
        window.aui._lasttoast = toast;
        $.toast(toast);
    }
    setTimeout(function () {
        if (window.aui._lasttoast.text) {
            console.log("clear toast");
            window.aui._lasttoast = {};
        }
    }, 1000);
};


window.aui.defineDatatableRules = function (rules) {
    var res = [];
    _.forEach(rules, function (rule, rulekey) {
        var k = {};
        if (_.isString(rule)) {
            k = {
                key: rule
            }
        } else {
            k = rule;
            if (_.isFunction(rule.key)) {
                k.key = rule.key()
            }
        }
        if(!k.value) {
            k.value = function (item) {
                return item[rulekey]
            };
        }
        res.push(k);
    });
    return res;
};

window.aui.defineGridRules = function (rules) {
    var res = {};
    _.forEach(rules, function (rule, rulekey) {
        if (_.isString(rule)) {
            res[rulekey] = {
                key: function () {
                    return rule;
                }
            }
        } else {
            res[rulekey] = rule;
        }
        if(!res[rulekey].value) {
            res[rulekey].value = function (item) {
                return item[rulekey]
            };
        }
    });
    return res;
};

window.aui.defineSearchFormRules = function (rules) {
    var res = {};
    _.forEach(rules, function (rule, rulekey) {
        if (_.isString(rule)) {
            res[rulekey] = {
                validate: {
                    presence: false,
                },
                attr: {
                    controlnotvalidate: true,
                    value: "",
                }
            }
        }
    });
    return res;
};

window.aui.defineFormRules = function (rules) {
    var res = {};
    var defaultrule = {
        validate: {
            presence: true,
        },
        attr: {
            value: "",
        }
    };
    _.forEach(rules, function (rule, rulekey) {
        if (_.isString(rule)) {
            res[rulekey] = _.cloneDeep(defaultrule);
        } else {
            res[rulekey] = _.cloneDeep(rule);
        }
    });
    return res;
};

window.aui.createFormField = function (label, prop, form = 'form', append = '') {
    return `
<div class="form-group" :aui-required="${form}.isFieldRequired('${prop}')">
    <label class="col-xs-2 control-label">${label}</label>                
    <div class="col-xs-5">
        <input type="text" class="form-control" placeholder=""
            v-model="${form}.data.${prop}.value"            
            v-input-validate="${form}.element.${prop}"
        >
    </div>
    ${append}
</div>
        `
};

window.aui.createFormGroup = function (label, prop, content = '', form = 'form', append = '', contentclass = 'col-xs-5', attr = '') {
    return `
<div class="form-group" :aui-required="${form}.isFieldRequired('${prop}')" ${attr}>
    <label class="col-xs-2 control-label">${label}</label>                
    <div class="${contentclass}">
        ${content}
    </div>
    ${append}
</div>
        `
};

window.aui.createPlainFormGroup = function (label, content = '',  attr = '', append = '', contentclass = 'col-xs-5') {
    return `
<div class="form-group" ${attr}>
    <label class="col-xs-2 control-label">${label}</label>                
    <div class="${contentclass}">
        ${content}  
    </div>
    ${append}
</div>
        `
};

window.aui.globalRegex = {
    "idcard": {
        presence: true,
        pattern: {
            regex: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
            flags: "g",
            message: ""
        }
    },
    "linkpassword": {
        "password": {
            validate: {
                presence: true
            },
            onValidate: function (newval, oldval, constraint, form) {
                if (form.element["confirmpassword"].element.hasClass("ng-dirty")) {
                    form.validateField("confirmpassword");
                }
                if (!newval) {
                    if (!_.isNumber(newval)) {
                        return [{
                        }];
                    }
                }
            },
            attr: {
                value: ""
            }
        },
        "confirmpassword": {
            validate: {
                presence: true,
            },
            onValidate: function (newval, oldval, constraint, form) {
                if (form.data["password"].value == newval) {
                    return false;
                }
                return [{
                    message: "not equal newpassword"
                }];
            },
            attr: {
                value: ""
            }
        },
    },
};

window.aui.globalformDefines = {
    "required": function (required = true, value = '', options) {
        var res = {
            validate: {
                presence: required
            },
            attr: {
                value: value
            }
        };
        return Object.assign(res, options);
    },
    "money": function (required = true, value = '', options) {
        var res = {
            validate:{
                presence: required,
                numericality: {
                    greaterThan: 0
                }
            },
            attr: {
                value: value
            }
        };
        return Object.assign(res, options);
    },
    "idcard": function (required = true, value = '', options) {
        var res = {
            validate: {
                presence: required,
                pattern: {
                    regex: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
                    flags: "g",
                    message: ""
                }
            },
            attr: {
                value: value
            }
        };
        return Object.assign(res, options);
    }
};

window.aui.handleChartResponse = function (response) {
    var res = {};
    res.data = [];
    response.origin = _.cloneDeep(response);
    _.forEach(response.data.categories, function (v, k) {
        res.data[k] = {};
        res.data[k].date = v;
    });
    _.forEach(response.data.series, function (serie, seriekey) {
        _.forEach(serie.data, function (v, k) {
            res.data[k][seriekey] = v;
        });
    });
    response.data = res;
    return response;
};

window.aui.calcSeriesByProp = function (series, prop) {
    var res = 0;
    if (!series[prop]) {
        console.error("no series prop");
        return 0;
    }
    _.forEach(series[prop].data, function (v) {
        res = res + parseFloat(v);
    });
    return res;
};

window.aui.griddefines = {
    single: function (key, appendstyle, setvalue, len = 30, options = {}) {
        var res = {
            key: function (item) {
                return key;
            },
            value: function (item) {
                return {
                    componentname: "aui-overflow-text",
                    appendclass: "aui-grid-item-overflow",
                    appendstyle: appendstyle,
                    value: setvalue(item),
                    len: len
                };
            }
        };
        return Object.assign(res, options);
    },
    enums: function (key, enums, setvalue, options) {
        var res = {
            key: function (item) {
                return key;
            },
            value: function (item) {
                return {
                    componentname: 'aui-enums-translate',
                    enums: enums,
                    value: setvalue(item)
                }
            }
        };
        return Object.assign(res, options);
    },
    money: function (key, setvalue, options) {
        var res = {
            key: function (item) {
                return key;
            },
            value: function (item) {
                return setvalue(item) + "元";
            }
        };
        return Object.assign(res, options);
    },
    remark: function (key, setvalue, options) {
        var res = {
            key: function (item) {
                return key;
            },
            value: function (item) {
                return `<pre class="aui-readonly-textarea" style="vertical-align: top;" readonly>${setvalue(item)}</pre>`
            }
        };
        return Object.assign(res, options);
    }
};

window.aui.templateUtils = {
};

window.aui.templateUtils.getLabelFromEnumsByValue = function (enums, value) {
    var ret = "";
    _.forEach(enums, function (v, k) {
        if (_.isNumber(value) && value == 0) {
            if (v.value === value) {
                ret = v.label;
            }
        }
        if (v.value == value) {
            ret = v.label;
        }
    });
    return ret;
};

window.aui.Net = {};

window.aui.Net.onTokenExpired = function () {

};

window.aui.Net.handleExipred = function (cb) {
    // console.log(rootcontroller.Cookies.get("console.aunbox.cn.dev"));
    if (!rootcontroller.Cookies.get("console.aunbox.cn.dev")) {
        rootcontroller.tokenManager.clear();
    }
    if (rootcontroller.tokenManager.isExpired()) {
        window.aui.Net.onTokenExpired();
        if (cb) {
            cb();
        }
    }
};

window.aui.Net.get = function (method, id, params) {
    window.aui.Net.handleExipred();
    return rootcontroller.services.requestService._get(method, id, Object.assign({
        token: rootcontroller.tokenManager.getToken(),
    }, params));
};

window.aui.Net.all = function (method, params, url) {
    window.aui.Net.handleExipred();
    return rootcontroller.services.requestService._all(method, Object.assign({
        token: rootcontroller.tokenManager.getToken(),
    }, params), url);
};

window.aui.Net.post = function (method, data, params) {
    window.aui.Net.handleExipred();
    return rootcontroller.services.requestService._post(method, data, Object.assign({
        token: rootcontroller.tokenManager.getToken(),
    }, params));
};

window.aui.Net.put = function (method, id, data, params) {
    window.aui.Net.handleExipred();
    return rootcontroller.services.requestService._put(method, id, data, Object.assign({
        token: rootcontroller.tokenManager.getToken(),
    }, params));
};

window.aui.Net.put = function (method, id, data, params) {
    window.aui.Net.handleExipred();
    return rootcontroller.services.requestService._put(method, id, data, Object.assign({
        token: rootcontroller.tokenManager.getToken(),
    }, params));
};

window.aui.Net.debug = function (type) {
    return window.aui.Net.all('', {}, `http://192.168.10.26:7001/v1/tokens?type=${type}&__method=GET&a=1`)
};

window.aui.interceptors = {};